package com.dangdang.sharding.dp.filter.spring.proxy;

import java.lang.reflect.Method;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.context.ApplicationContext;

import com.dangdang.sharding.dp.filter.dp.Request;
import com.dangdang.sharding.dp.filter.dp.Response;
import com.dangdang.sharding.dp.filter.dp.service.Controller;
import com.dangdang.sharding.dp.filter.spring.core.InterceptorRegistry;
import com.dangdang.sharding.dp.filter.spring.core.RegistryConfigurer;

public class FilterCglibProxy implements MethodInterceptor {
    private Controller controller;
    private ApplicationContext applicationContext;
    
    public FilterCglibProxy(Controller controller, ApplicationContext applicationContext) {
		super();
		this.controller = controller;
		this.applicationContext = applicationContext;
	}
    

	private void doFilter(Object[] args) {
		InterceptorRegistry ir = applicationContext.getBean(InterceptorRegistry.class);
		ir.doFilter((Request)args[0],(Response) args[1]);
	}

	
	public Object getProxyInstance() {
        // 创建 Enhancer 对象
        Enhancer enhancer = new Enhancer();
        // 设置目标对象的Class
        enhancer.setSuperclass(controller.getClass());
        // 设置回调操作，相当于InvocationHandler
        enhancer.setCallback(this);
        return enhancer.create();
    }
	
    @Override
    public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy)
            throws Throwable {
    	registerFilter();
        doFilter(args);
        Object invoke = method.invoke(controller, args);
        return invoke;
    }


	private void registerFilter() {
		RegistryConfigurer rc=applicationContext.getBean(RegistryConfigurer.class);
		rc.registerFilter(applicationContext.getBean(InterceptorRegistry.class));
	}
}